package com.cf.web.util;



import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FTPUtil {

    // FTP上传
    public static boolean uploadFile(String server, int port, String user, String password, String filePath, String remoteDir) {
        FTPClient ftpClient = new FTPClient();
        FileInputStream fis = null;
        try {
            ftpClient.connect(server, port);
            ftpClient.login(user, password);
            ftpClient.enterLocalPassiveMode();  // 设置为被动模式
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  // 设置文件类型为二进制

            File file = new File(filePath);
            fis = new FileInputStream(file);
            String remoteFile = remoteDir + "/" + file.getName();

            // 上传文件
            return ftpClient.storeFile(remoteFile, fis);
        } catch (IOException ex) {
            ex.printStackTrace();
            return false;
        } finally {
            try {
                if (fis != null) fis.close();
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
